package com.dokimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.dokimall.common.exception.NostockExcption;
import com.dokimall.common.to.mq.OrderTo;
import com.dokimall.common.to.mq.StockLockDetail;
import com.dokimall.common.to.mq.StockLockedTo;
import com.dokimall.common.utils.R;
import com.dokimall.ware.entity.WareOrderTaskDetailEntity;
import com.dokimall.ware.entity.WareOrderTaskEntity;
import com.dokimall.ware.feign.OrderFeignService;
import com.dokimall.ware.feign.ProductFeignService;
import com.dokimall.ware.service.WareOrderTaskDetailService;
import com.dokimall.ware.service.WareOrderTaskService;
import com.dokimall.ware.vo.*;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dokimall.common.utils.PageUtils;
import com.dokimall.common.utils.Query;

import com.dokimall.ware.dao.WareSkuDao;
import com.dokimall.ware.entity.WareSkuEntity;
import com.dokimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String)params.get("skuId");
        String wareId = (String)params.get("wareId");
        if(StringUtils.isNotEmpty(skuId)){
            queryWrapper.eq("sku_id",skuId);
        }
        if(StringUtils.isNotEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    // 添加成功采购需求商品到库
    @Transactional
    @Override
    public void addToWare(Long skuId, Long wareId, Integer skuNum) {
        int count = this.count(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id",wareId));
        if(count>0){
            this.baseMapper.addToWare(skuId,wareId,skuNum);
        }else {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            R r = productFeignService.info(skuId);
            // 如果保存名字发生异常不进行回滚，继续保存
            // TODO 还有什么方法让异常出现后不回滚
            try {
                if(r.getCode()==0){
                    Map<String,Object> skuInfo =(Map<String,Object>) r.get("skuInfo");
                    wareSkuEntity.setSkuName((String)skuInfo.get("skuName"));
                }
            }catch(Exception e){
            }

            this.save(wareSkuEntity);
        }

    }

    @Override
    public List<SkuHasStockVo> cheakHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> skuHasStockVos = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            // 查询当前sku的总库存量
            Long count = this.baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            if(count!=null){
                vo.setHasStock(count>0?true:false);
            }else {
                vo.setHasStock(false);
            }
            return vo;
        }).collect(Collectors.toList());
        return skuHasStockVos;
    }


    /**
     * 为某个订单锁定库存
     * */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {
        String orderSn = wareSkuLockVo.getOrderSn();
        WareOrderTaskEntity orderTaskEntity = new WareOrderTaskEntity();
        orderTaskEntity.setOrderSn(orderSn);
        wareOrderTaskService.save(orderTaskEntity);
        List<OrderItemVo> locks = wareSkuLockVo.getLocks();
        // 查找哪个仓库拥有库存,然后进行锁定
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            stock.setSkuId(item.getSkuId());
            Integer conut = item.getConut();
            List<Long> wareIds = baseMapper.getHasStockWareId(item.getSkuId(), conut);
            stock.setWareId(wareIds);
            stock.setNum(item.getConut());
            return stock;
        }).collect(Collectors.toList());
        // 将商品锁定库存，若这个仓库不行就下一个
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if(wareIds==null && wareIds.size()==0){
                throw new NostockExcption(skuId);
            }
            for (Long wareId : wareIds) {
                // 成功就返回1 ，失败就返回0
                Long count = baseMapper.lockSkuStock(wareId,skuId,hasStock.getNum());
                if(count == 1){
                    // 成功了
                    skuStocked = true;
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(orderTaskEntity.getId());
                    StockLockDetail lockDetail = new StockLockDetail(null,skuId,"",hasStock.getNum(),orderTaskEntity.getId(),wareId,1);
                    WareOrderTaskDetailEntity orderTaskDetailEntity = new WareOrderTaskDetailEntity();
                    BeanUtils.copyProperties(lockDetail,orderTaskDetailEntity);
                    wareOrderTaskDetailService.save(orderTaskDetailEntity);
                    lockDetail.setId(orderTaskDetailEntity.getId());
                    stockLockedTo.setStockLockDetail(lockDetail);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo);
                    break;
                }else {
                    break;
                }
            }
            if(skuStocked == false){
                throw new NostockExcption(skuId);
            }
        }

        return true;
    }

    @Override
    public void unLocked(StockLockedTo to){
        StockLockDetail stockLockDetail = to.getStockLockDetail();
        Long detailId = stockLockDetail.getId();
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if(byId!=null){
            // 进行解锁，需要去订单服务查看订单状态
            Long id = to.getId(); // 库存工作单的消息
            WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getById(id);
            String orderSn = orderTaskEntity.getOrderSn();
            R r = orderFeignService.getInfoBySn(orderSn);
            if(r.getCode() == 0){
                // 成功返回
                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });
                if (data == null || data.getStatus()==4){
                    // 订单已支付成功或者状态为“已取消”，需要解锁库存
                    System.out.println("进行解锁。。。");
                    if (byId.getLockStatus() == 1){
                        // 状态为已锁定才进行解锁操作
                        unLockStock(byId.getSkuId(),byId.getWareId(),byId.getSkuNum(),byId.getId());
                    }
                }
                else {
                    // 远程调用或者网络问题...拒收消息重返队列
                }
            }
        }else {
            // 数据库没有对应的工作单，库存锁定失败回滚了，无需解锁库存
        }
    }

    @Override
    public void unLocked(OrderTo to) {
        // 查询wareTask表找到对应id，去detail表查询到对应锁定的商品状态
        String orderSn = to.getOrderSn();
        WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getByOrderSn(orderSn);
        if(wareOrderTaskEntity!=null){
            Long id = wareOrderTaskEntity.getId();
            List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id).eq("lock_status", 1));
            if(list!=null && list.size()>0){
                for (WareOrderTaskDetailEntity detailEntity : list) {
                    // 进行解锁
                    unLockStock(detailEntity.getSkuId(),detailEntity.getWareId(),detailEntity.getSkuNum(),detailEntity.getId());
                }
            }
        }
    }

    // 解锁库存方法
    private void unLockStock(Long skuId, Long wareId, Integer skuNum ,Long detailId) {
        // 解锁
        baseMapper.unLockStock(skuId,wareId,skuNum);
        // 改变库存detail表的状态 1-已锁定 2-已解锁
        WareOrderTaskDetailEntity orderTaskDetailEntity = new WareOrderTaskDetailEntity();
        orderTaskDetailEntity.setId(detailId);
        orderTaskDetailEntity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(orderTaskDetailEntity);
    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}